package com.zhongxi.guoyuan.adapter.beautifulStoreOrder;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.navisdk.adapter.BNRoutePlanNode;
import com.baidu.navisdk.adapter.BaiduNaviManager;
import com.bumptech.glide.Glide;
import com.zhongxi.guoyuan.R;
import com.zhongxi.guoyuan.application.MyApplication;
import com.zhongxi.guoyuan.entity.beautifulOrder.BeautifulStoreOrderData;
import com.zhongxi.guoyuan.entity.beautifulOrder.BeautifulStoreOrderInfoResult;
import com.zhongxi.guoyuan.fragment.MainPersonFragment;
import com.zhongxi.guoyuan.url.Url;
import com.zhongxi.guoyuan.utils.GlideRoundTransform;
import com.zhongxi.guoyuan.utils.MyTextUtils;
import com.zhongxi.guoyuan.view.MapNaviActivity;
import com.zhongxi.guoyuan.view.beautifulStore.BeautifulCommentActivity;
import com.zhongxi.guoyuan.view.personalCenter.BeautifulStoreOrderActivity;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2016/11/21.
 */

public class StoreOrderHasCompleteAdapter extends BaseAdapter {

    private Context context;
    private List<BeautifulStoreOrderData> list ;
    private LayoutInflater mLayoutInflater;

    private int mExpandedMenuPos = -1;
    private BeautifulStoreOrderInfoResult infoResult;

    private Handler handler;

    public StoreOrderHasCompleteAdapter(Context context, List<BeautifulStoreOrderData> data, Handler handler) {
        this.context = context;
        this.mLayoutInflater = LayoutInflater.from(context);
        this.list = data;
        this.handler = handler;
    }

    public int getmExpandedMenuPos() {
        return mExpandedMenuPos;
    }

    public void setmExpandedMenuPos(int mExpandedMenuPos, BeautifulStoreOrderInfoResult infoResult) {
        this.mExpandedMenuPos = mExpandedMenuPos;
        this.infoResult = infoResult;
    }

    @Override
    public int getCount() {
        return list.size();
    }

    @Override
    public Object getItem(int position) {
        return list.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        ViewHolder holder = null;
        if(convertView == null){
            holder = new ViewHolder();
            convertView = mLayoutInflater.inflate(R.layout.item_beautiful_store_order, parent, false);
            holder.ivServiceImg = (ImageView) convertView.findViewById(R.id.ivServiceImg);
            holder.tvServiceName = (TextView) convertView.findViewById(R.id.tvServiceName);
            holder.tvServiceTime = (TextView) convertView.findViewById(R.id.tvServiceTime);
            holder.tvServiceType = (TextView) convertView.findViewById(R.id.tvServiceType);
            holder.tvOrderNum = (TextView) convertView.findViewById(R.id.tvOrderNum);
            holder.tvOrderInfo = (TextView) convertView.findViewById(R.id.tvOrderInfo);
            holder.tvOrderTime = (TextView) convertView.findViewById(R.id.tvOrderTime);
            holder.tvOrderName = (TextView) convertView.findViewById(R.id.tvOrderName);
            holder.tvSubTime = (TextView) convertView.findViewById(R.id.tvSubTime);
            holder.tvOrign = (TextView) convertView.findViewById(R.id.tvOrign);
            holder.tvTruePrice = (TextView) convertView.findViewById(R.id.tvTruePrice);
            holder.tvForword = (TextView) convertView.findViewById(R.id.tvForword);
            holder.tvComplain = (TextView) convertView.findViewById(R.id.tvComplain);
            holder.tvOper = (TextView) convertView.findViewById(R.id.tvOper);
            holder.ivDown = (ImageView) convertView.findViewById(R.id.iv_down);
            holder.listMenu = (View) convertView.findViewById(R.id.list_menu);
            holder.listGoMenu = (View) convertView.findViewById(R.id.list_go_menu);
            holder.ivCall = (ImageView) convertView.findViewById(R.id.ivCall);
            holder.ivMapNavi = (ImageView) convertView.findViewById(R.id.ivMapNavi);
            holder.tvMyPhone = (TextView) convertView.findViewById(R.id.tvMyPhone);
            holder.tvOrderAddress = (TextView) convertView.findViewById(R.id.tvOrderAddress);
            holder.tvMsg = (TextView) convertView.findViewById(R.id.tvMsg);
            holder.tvOrderStoreName = (TextView) convertView.findViewById(R.id.tvOrderStoreName);
            holder.tvOrderStorePhone = (TextView) convertView.findViewById(R.id.tvOrderStorePhone);
            holder.tvMyAddress = (TextView) convertView.findViewById(R.id.tvMyAddress);
            holder.relaMyInfo = (RelativeLayout) convertView.findViewById(R.id.relaMyInfo);
            convertView.setTag(holder);
        }else{
            holder = (ViewHolder) convertView.getTag();
        }
        final BeautifulStoreOrderData itemData = list.get(position);
        holder.tvOper.setText("去评价");
        holder.tvOper.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(context, BeautifulCommentActivity.class);
                Bundle bundle = new Bundle();
                bundle.putSerializable("info", list.get(position));
                intent.putExtras(bundle);
                context.startActivity(intent);
            }
        });
        holder.tvComplain.setVisibility(View.VISIBLE);
        if("4".equals(itemData.getStatus())){
            holder.tvComplain.setText("已投诉");
        }else{
            holder.tvComplain.setText("我投诉");
        }
        holder.tvComplain.setOnClickListener(new View.OnClickListener() {
            public EditText etTips;
            public TextView tvNum;

            @Override
            public void onClick(View v) {
                if ("4".equals(itemData.getStatus())) {
                    Toast.makeText(context, "您已投诉过了，店家已受理，请耐心等待！", Toast.LENGTH_SHORT).show();
                } else {
                    View view = ((Activity) context).getLayoutInflater().inflate(R.layout.item_complain, null);
                    final Dialog dialog = new AlertDialog.Builder(context).create();
                    dialog.show();
                    dialog.getWindow().setContentView(view);

                    dialog.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
                    dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);

                    ImageView ivCancel = (ImageView) view.findViewById(R.id.ivCancel);
                    etTips = (EditText) view.findViewById(R.id.etTips);
                    tvNum = (TextView) view.findViewById(R.id.tvNum);
                    Button btSubmit = (Button) view.findViewById(R.id.btSubmit);
                    ivCancel.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            dialog.dismiss();
                        }
                    });
                    etTips.addTextChangedListener(new TextWatcher() {
                        @Override
                        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                        }

                        @Override
                        public void onTextChanged(CharSequence s, int start, int before, int count) {

                        }

                        @Override
                        public void afterTextChanged(Editable content) {
                            MyTextUtils.TextChangeUtils(context, tvNum, content);
                        }
                    });
                    btSubmit.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            String content = etTips.getText().toString().trim();
                            Message msg = Message.obtain();
                            msg.what = 1;
                            msg.arg1 = position;
                            msg.obj = content;
                            handler.sendMessage(msg);
                            dialog.dismiss();
                        }
                    });
                }
            }
        });
        holder.ivCall.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(null!=infoResult&&!"".equals(infoResult)&&null!=infoResult.getExtInfo())
                    if(null!=infoResult.getExtInfo().getPhonenum()&&!"".equals(infoResult.getExtInfo().getPhonenum())){
                        Intent intent = new Intent(Intent.ACTION_DIAL);
                        Uri data = Uri.parse("tel:" + infoResult.getExtInfo().getPhonenum());
                        intent.setData(data);
                        context.startActivity(intent);
                    }else{
                        Toast.makeText(context, "暂不可联系", Toast.LENGTH_SHORT).show();
                    }
            }
        });
        holder.ivMapNavi.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(BaiduNaviManager.isNaviInited()){
                    routeplanToNavi(BNRoutePlanNode.CoordinateType.BD09LL);
                }
            }
        });
        holder.relaMyInfo.setVisibility(position == mExpandedMenuPos?View.VISIBLE:View.GONE);
        holder.ivDown.setImageResource(position == mExpandedMenuPos ? R.mipmap.iv_down_light:R.mipmap.iv_down);
        //初始化数据
        if(null!=itemData.getServiceimg()&&!"".equals(itemData.getServiceimg())){
            Glide.with(context).load(Url.IMG_URL+itemData.getServiceimg()).placeholder(R.mipmap.iv_eg).transform(new GlideRoundTransform(context, 20)).into(holder.ivServiceImg);
        }
        if(null!=itemData.getServicename()&&!"".equals(itemData.getServicename())){
            holder.tvServiceName.setText(itemData.getServicename());
        }else{
            holder.tvServiceName.setText("");
        }
        if(null!=itemData.getCtime()&&!"".equals(itemData.getCtime())){
            holder.tvServiceTime.setText("完成时间："+itemData.getCtime());
        }else{
            holder.tvServiceTime.setText("完成时间：**");
        }
        if(null!=itemData.getSstype()&&!"".equals(itemData.getSstype())){
            if("1".equals(itemData.getSstype())){
                holder.tvServiceType.setText("服务方式：上门服务");
                holder.listGoMenu.setVisibility(position == mExpandedMenuPos ? View.VISIBLE:View.GONE);
            }else{
                holder.tvServiceType.setText("服务方式：到店服务");
                holder.listMenu.setVisibility(position == mExpandedMenuPos ? View.VISIBLE:View.GONE);
            }
        }
        if(null!=itemData.getId()&&!"".equals(itemData.getId())){
            holder.tvOrderNum.setText("订单号：" + itemData.getId());
            holder.tvOrderInfo.setText("订单信息："+itemData.getId());
        }else{
            holder.tvOrderNum.setText("订单号：");
            holder.tvOrderInfo.setText("订单信息：");
        }
        if(null!=itemData.getCtime()&&!"".equals(itemData.getCtime())){
            holder.tvOrderTime.setText(itemData.getCtime()+"完成");
        }else {
            holder.tvOrderTime.setText("");
        }
        if(null!=itemData.getServicename()&&!"".equals(itemData.getServicename())){
            holder.tvOrderName.setText(itemData.getServicename());
        }else{
            holder.tvOrderName.setText("");
        }
        try{
            if(null!=infoResult&&!"".equals(infoResult)){
                if(null!=infoResult.getExtInfo()&&!"".equals(infoResult.getExtInfo())){
                    if(null!=infoResult.getExtInfo().getMphone()&&!"".equals(infoResult.getExtInfo().getMphone())){
                        holder.tvMyPhone.setText(infoResult.getExtInfo().getMphone());
                    }
                    if(null!=infoResult.getExtInfo().getAddress()&&!"".equals(infoResult.getExtInfo().getAddress())){
                        holder.tvOrderAddress.setText(infoResult.getExtInfo().getAddress());
                    }
                    if(null!=infoResult.getExtInfo().getMsg()&&!"".equals(infoResult.getExtInfo().getMsg())){
                        holder.tvMsg.setText(infoResult.getExtInfo().getMsg());
                    }
                    if(null!=infoResult.getExtInfo().getName()&&!"".equals(infoResult.getExtInfo().getName())){
                        holder.tvOrderStoreName.setText(infoResult.getExtInfo().getName());
                    }
                    if(null!=infoResult.getExtInfo().getPhonenum()&&!"".equals(infoResult.getExtInfo().getPhonenum())){
                        holder.tvOrderStorePhone.setText(infoResult.getExtInfo().getPhonenum());
                    }
                    if(null!=infoResult.getSubscribeInfo().getSubscribetime()&&!"".equals(infoResult.getSubscribeInfo().getSubscribetime())){
                        holder.tvSubTime.setText(infoResult.getSubscribeInfo().getSubscribetime());
                    }else{
                        holder.tvSubTime.setText("");
                    }
                    if(null!=infoResult.getExtInfo().getAddress()&&!"".equals(infoResult.getExtInfo().getAddress())){
                        holder.tvMyAddress.setText(infoResult.getExtInfo().getAddress());
                    }else{
                        holder.tvMyAddress.setText("");
                    }
                }
            }
            holder.tvTruePrice.setVisibility(View.GONE);
           // holder.tvOrign.setText("实付："+itemData.getPayinnerprice()+"美币+"+itemData.getPay()+"元");
            holder.tvOrign.setText("实付："+itemData.getPay()+"元");
            if(MyApplication.getInstance().isPrivilege()){
                holder.tvForword.setText("返银："+new BigDecimal(itemData.getPay()).multiply(new BigDecimal(itemData.getBacksilverratio())).intValue()/100);
            }else{
                holder.tvForword.setText("返银：0");
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return convertView;
    }

    private void routeplanToNavi(BNRoutePlanNode.CoordinateType coType) {
        BNRoutePlanNode sNode = null;
        BNRoutePlanNode eNode = null;
        switch (coType) {
            case GCJ02: {
                sNode = new BNRoutePlanNode(116.30142, 40.05087, "百度大厦", null, coType);
                eNode = new BNRoutePlanNode(116.39750, 39.90882, "北京天安门", null, coType);
                break;
            }
            case WGS84: {
                sNode = new BNRoutePlanNode(116.300821, 40.050969, "百度大厦", null, coType);
                eNode = new BNRoutePlanNode(116.397491, 39.908749, "北京天安门", null, coType);
                break;
            }
            case BD09_MC: {
                sNode = new BNRoutePlanNode(12947471, 4846474, "百度大厦", null, coType);
                eNode = new BNRoutePlanNode(12958160, 4825947, "北京天安门", null, coType);
                break;
            }
            case BD09LL: {
                sNode = new BNRoutePlanNode(Double.parseDouble(MyApplication.getInstance().getLongitude()), Double.parseDouble(MyApplication.getInstance().getLatitude()), "出发地", null, coType);
                eNode = new BNRoutePlanNode(Double.parseDouble(infoResult.getExtInfo().getLongitude()), Double.parseDouble(infoResult.getExtInfo().getDimensions()), "美容院", null, coType);
                break;
            }
            default:
                ;
        }
        if (sNode != null && eNode != null) {
            List<BNRoutePlanNode> list = new ArrayList<BNRoutePlanNode>();
            list.add(sNode);
            list.add(eNode);
            BaiduNaviManager.getInstance().launchNavigator((Activity) context, list, 1, true, new DemoRoutePlanListener(sNode));
        }
    }

    public class DemoRoutePlanListener implements BaiduNaviManager.RoutePlanListener {

        private BNRoutePlanNode mBNRoutePlanNode = null;

        public DemoRoutePlanListener(BNRoutePlanNode node) {
            mBNRoutePlanNode = node;
        }

        @Override
        public void onJumpToNavigator() {
			/*
			 * 设置途径点以及resetEndNode会回调该接口
			 */

            for (Activity ac : BeautifulStoreOrderActivity.activityList) {

                if (ac.getClass().getName().endsWith("MapNaviActivity")) {

                    return;
                }
            }
            Intent intent = new Intent(context, MapNaviActivity.class);
            Bundle bundle = new Bundle();
            bundle.putSerializable(MainPersonFragment.ROUTE_PLAN_NODE, (BNRoutePlanNode) mBNRoutePlanNode);
            intent.putExtras(bundle);
            intent.putExtra("type", "1");
            context.startActivity(intent);

        }

        @Override
        public void onRoutePlanFailed() {
            Toast.makeText(context, "导航失败", Toast.LENGTH_SHORT).show();
        }
    }

    class ViewHolder {
        private ImageView ivServiceImg;
        private ImageView ivDown;
        private View listMenu;
        private View listGoMenu;
        private TextView tvComplain;
        private ImageView ivCall;
        private ImageView ivMapNavi;
        private TextView tvOper;
        private TextView tvServiceName;
        private TextView tvServiceTime;
        private TextView tvServiceType;
        private TextView tvOrderNum;
        private TextView tvOrderInfo;
        private TextView tvOrderTime;
        private TextView tvOrderName;
        private TextView tvOrign;
        private TextView tvTruePrice;
        private TextView tvForword;
        private TextView tvSubTime;
        private TextView tvMyPhone;
        private TextView tvOrderAddress;
        private TextView tvMsg;
        private TextView tvOrderStoreName;
        private TextView tvOrderStorePhone;
        private RelativeLayout relaMyInfo;
        private TextView tvMyAddress;
    }
}
